/***************************************************************************
 *  Filename: main.cpp
 *  Class:
 *
 *  Copyright 2012  Mario Henrique Voorsluys
 *  <forcaeluz@gmail.com>
 *
 ****************************************************************************/


#include <QtCore/QCoreApplication>
#include <QThread>
#include <QObject>
#include <QtCore>
#include <QIODevice>
#include <cstdio>
#include "maincontroller.h"
#include "navadatareceiver.h"
#include "controlsender.h"
#include "simplecommunicationhandler.h"

#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <qextserialport/qextserialport.h>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.addLibraryPath(".");
    qDebug() << "Library path is" << a.libraryPaths();
    qDebug() << WIFI_MYKONOS_IP;

    QThread *controlsThread = new QThread(&a);
    ControlSender *ctrlsender = new ControlSender();
    ctrlsender->moveToThread(controlsThread);
    QObject::connect(controlsThread, SIGNAL(started()), ctrlsender, SLOT(startRunning()));
    controlsThread->start();

    QThread *navdatarThread = new QThread(&a);
    NavDataReceiver *navdatareceiver = new NavDataReceiver();
    navdatareceiver->moveToThread(navdatarThread);
    QObject::connect(navdatarThread, SIGNAL(started()), navdatareceiver, SLOT(startRunning()));
    navdatarThread->start();

    QThread *uartThread = new QThread(&a);
    SimpleCommunicationHandler *uartHandler = new SimpleCommunicationHandler();
    uartHandler->moveToThread(uartThread);
    uartThread->start();
    QObject::connect(navdatareceiver, SIGNAL(updateBattery(int)), uartHandler, SLOT(sendBattery(int)), Qt::DirectConnection);
    QObject::connect(navdatareceiver, SIGNAL(updateAngleData(float,float,float)), uartHandler, SLOT(sendGyros(float,float,float)), Qt::DirectConnection);
    QObject::connect(navdatareceiver, SIGNAL(updateAltitude(int)), uartHandler, SLOT(sendAltitude(int)), Qt::DirectConnection);
    QObject::connect(navdatareceiver, SIGNAL(updateVelocities(float,float,float)), uartHandler, SLOT(sendVelocity(float,float,float)), Qt::DirectConnection);
    QObject::connect(navdatareceiver, SIGNAL(initSequence(int)), ctrlsender, SLOT(sendInitSequence(int)), Qt::DirectConnection);
    QObject::connect(navdatareceiver, SIGNAL(updateState(uint)), ctrlsender, SLOT(updateState(uint)), Qt::DirectConnection);




    //    QextSerialPort serial;
    //    serial.setPortName("/dev/ttyPA0");
    //    serial.setBaudRate(BAUD9600);
    //    serial.open(QIODevice::ReadWrite);
    //    if(serial.isOpen()){
    //        qDebug() << "Serial port is open";
    //    }else{
    //        qWarning() << "Serial port not open" << serial.errorString();
    //    }
    //    while(true){
    //        if(serial.bytesAvailable()){
    //            char buff[256];
    //            int t = serial.read(buff, 255);
    //            buff[t]='\0';
    //            qDebug() << buff;
    //        }
    //    }
    return a.exec();
}
